package com.example.star.controller;

import com.example.star.entity.Favorite;
import com.example.star.entity.ShoppingCart;
import com.example.star.entity.User;
import com.example.star.service.ShoppingCartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/shopping_carts")
    @ResponseBody
    public ShoppingCart saveShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        shoppingCartService.saveShoppingCart(shoppingCart);
        return shoppingCart; // 返回保存的ShoppingCart对象
    }

    @GetMapping("/shopping_carts")
    @ResponseBody
    public List<ShoppingCart> getShoppingCarts() {
        return shoppingCartService.getAllShoppingCarts();
    }

    @GetMapping("/shopping_carts/items-by-user")
    @ResponseBody
    public List<ShoppingCart> getShoppingCartByuserName(@RequestParam String userName) {
        return shoppingCartService.getShoppingCartByuserName(userName);
    }

    @DeleteMapping("/shopping_carts/{id}")
    @ResponseBody
    public void deleteShoppingCartById(@PathVariable int id) {
        shoppingCartService.deleteShoppingCartById(id);
    }

    @GetMapping("/shoppingcart-list")
    public String showShoppingCartList(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "8") int size,
                                       Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");


        if (userObj == null) {
            // 用户未登录，重定向到登录页面
            return "redirect:/login";
        }

        User user = (User) userObj;
        List<ShoppingCart> shoppingCarts;
        int totalStars;
        if ("ADMIN".equals(user.getRole())) {
            // 管理员角色，获取所有购物车信息
            shoppingCarts = shoppingCartService.getShoppingCartByPage(page, size);
            totalStars = shoppingCartService.getTotalShoppingCarts();
        } else {
            // 普通用户角色，获取该用户的购物车信息
            shoppingCarts = shoppingCartService.getShoppingCartsByUserPage(user.getUsername(), page, size);
            totalStars = shoppingCartService.getTotalShoppingCartsByUser(user.getUsername());
        }


        int totalPages = (int) Math.ceil((double) totalStars / size);

        model.addAttribute("shopping_carts", shoppingCarts);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "shoppingcart-list";
    }

    @PostMapping("/shopping_carts/{id}")
    public String deleteShoppingCarts(@PathVariable int id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        // 从 HttpSession 中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            redirectAttributes.addFlashAttribute("error", "你还未登录，请先登录");
            return "redirect:/login"; // 重定向到登录页面
        }

        User user = (User) userObj;
        // 假设管理员角色名称为 "ADMIN"，根据实际情况修改
        if ("ADMIN".equals(user.getRole())) {
            try {
                shoppingCartService.deleteShoppingCartById(id);
                redirectAttributes.addFlashAttribute("message", "购物车信息删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除购物车信息时出现错误：" + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "你没有权限删除购物车信息");
        }
        return "redirect:/shoppingcart-list";
    }

}
